package com.myplaylist.server;

import java.io.ByteArrayOutputStream;
import java.io.PrintWriter;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

import com.myplaylist.utils.Constants;

public class UdpConnectionHandlerThread extends Thread {

	private DatagramPacket packet;

	public UdpConnectionHandlerThread(DatagramPacket packet) {
		this.packet = packet;
	}

	@Override
	public void run() {
		DatagramSocket datagramSocket = null;
		try {
			
			datagramSocket = new DatagramSocket();
			String message = new String(packet.getData()).trim();
			System.out.println(message);
			if (message.equals(Constants.CLIENT_MESSAGE)) {
				Thread.sleep(500);
				InetAddress senderAddress = packet.getAddress();
				System.out.println("PING arrived from IP address: " + senderAddress.getHostAddress());
				
				ByteArrayOutputStream baos = new ByteArrayOutputStream();
				PrintWriter pw = new PrintWriter(baos);
				
				InetAddress localhost = InetAddress.getLocalHost();
				System.out.println("Localhost is: " + localhost);
				String response = localhost.toString()+ ":" + Constants.TCP_SERVER_PORT;
				System.out.println("Response to ping: " + response);
				
				pw.write(response, 0, response.length());
				pw.flush();
				
				byte[] bytes = baos.toByteArray();
				
				packet = new DatagramPacket(bytes, bytes.length, senderAddress, Constants.UDP_SERVER_PORT_LISTEN);
				datagramSocket.send(packet);
				
				baos.close();
				
				//oos.close();
			}
		} catch (Exception e) {
			// TODO: handle exception
		} finally {
			closeStreams(datagramSocket);
		}
		
	}

	private void closeStreams(DatagramSocket datagramSocket) {
		if (datagramSocket != null) {
			datagramSocket.close();
		}
	}

}
